﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Corp;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.System.User
{
    [UseDI(ServiceLifetime.Scoped)]
    public class UserRepository : Repository<SysUser, DefaultDbContext>
    {
        public UserRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public bool Exists(SysUser user)
        {
            return DbContext.Exists<SysUser>("cardno=@0", user.Cardno);
        }

        public bool Exists(int id, SysUser user)
        {
            return DbContext.Exists<SysUser>("cardno=@0 and user_id!=@1", user.Cardno, id);
        }

        public SysUser? GetUser(string cardNo)
        {
            Sql sql = Sql.Builder.Select("user_id").From("sys_user").Where("cardno=@0", cardNo);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        public bool CodeExists(string code)
        {
            return DbContext.Exists<SysUser>("cardno=@0", StringUtility.StripSQLInjection(code));
        }

        public IEnumerable<SysUser> GetUsers(int deptId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("DeptId", deptId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"UsersByDeptId:{deptId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder;
                sql.Select("user_id")
                   .From("sys_user")
                   .Where("dept_id=@0", deptId);
                return sql;
            });
        }

        public IPagedList<SysUser> GetUsers(UserQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("user_id")
                .From("sys_user");
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(name Like @0 or cardno Like @0 or mobile Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.Status.HasValue)
                sql.Where("status=@0", query.Status);
            if (query.DeptId.HasValue)
                sql.Where("dept_id=@0", query.DeptId);
            sql.Where("is_deleted=0");
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }
    }
}